<?php


namespace app\blog\controller;


use app\blog\model\BannerModel;
use app\blog\validate\BannerValidate;
use cmf\controller\AdminBaseController;

class BannerController extends AdminBaseController
{
    //显示数据
    public function index(){
        $list = BannerModel::order('id DESC')->paginate(10);
        return $this->fetch('index',[
            'list' => $list,
        ]);
    }
    //添加
    public function add(){
        //查询数据
        $list = BannerModel::select();
        return $this->fetch('add',[
            'list' => $list,
        ]);
    }
    public function addPost(){
        $data = input('post.');
        $validate = new BannerValidate();

        $result = $validate->scene('add')->check($data);
        if(true !== $result){
            $this->error($validate->getError());
        }
        //入库
        if(BannerModel::create($data)){
            $this->success('添加成功','Banner/index');
        }else{
            $this->error('添加失败');
        }
    }
    //修改
    public function edit(){
        $id = input('id');
        $list = BannerModel::find($id);
        return $this->fetch('edit',[
            'list' => $list,
        ]);
    }
    public function editPost(){
        $data = input('post.');
        //验证器
        $validate = new BannerValidate();
        $result = $validate->scene('edit')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        //查询是否有此记录
        $list = BannerModel::find($data['id']);
        if(!$list){
            $this->error('未查询到该记录');
        }
        if($list->update($data)){
            $this->success('修改成功','Banner/index');
        }else{
            $this->error('修改失败');
        }
    }
//删除
    public function delete(){
        $id = input('id/d','');
        $del = BannerModel::destroy($id);
        if($del){
            $this->success('删除成功','Banner/index');
        }else{
            $this->error('删除失败');
        }
    }
}